'use strict'

const Controller = require('egg').Controller

class BlogsController extends Controller {
	// 博客添加接口
	async addBlogItem() {
		const { ctx, app } = this
		const { userId, title, content } = ctx.request.body
		const addItem = await app.mysql.insert('blogs', {
			userId,
			title,
			content
		})
		if (addItem.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '添加成功',
				data: { insertId: addItem.insertId }
			}
		} else {
			ctx.body = { code: 0, msg: '添加失败，请重试' }
		}
	}

	// 博客删除接口
	async removeBlogItem() {
		const { ctx, app } = this
		// delete 接口 动态id传递参数
		const { blogsId } = ctx.params
		const removeBlogsData = await app.mysql.delete('blogs', { blogsId })
		if (removeBlogsData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '删除成功'
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '删除失败，请重新尝试'
			}
		}
	}

	// 博客修改接口 blogsId
	async updateBlogItem() {
		const { ctx, app } = this
		const { blogsId } = ctx.params
		const { title, content } = ctx.request.body
		const updateData = await app.mysql.query(
			`update blogs set title=?, content=? where blogsId=?`,
			[title, content, blogsId]
		)
		if (updateData.affectedRows) {
			ctx.body = {
				code: 0,
				msg: '修改成功'
			}
		} else {
			ctx.body = {
				code: -1,
				msg: '修改失败'
			}
		}
	}

	// 查询接口
	async findBlogs() {
		const { ctx, app } = this
		// get 参数
		const { page, size, title } = ctx.query
		console.log(title, 'title')
		if (title) {
			const findBlogs = await app.mysql.select('blogs', {
				limit: size * 1,
				offset: (page - 1) * size,
				// columns: ['id', 'nickname', 'email', 'avatar', 'phone'] // 要查询哪个字段
				orders: [['blogsId', 'desc']], // 倒序排列
				where: { title } // WHERE 条件 精确查找
			})
			ctx.body = { code: 0, msg: 'success', data: findBlogs }
		} else {
			const findBlogs = await app.mysql.select('blogs', {
				limit: size * 1,
				offset: (page - 1) * size,
				// columns: ['id', 'nickname', 'email', 'avatar', 'phone'] // 要查询哪个字段
				orders: [['blogsId', 'desc']] // 倒序排列
				// where: { title } // WHERE 条件
			})
			ctx.body = { code: 0, msg: 'success', data: findBlogs }
		}
	}

	// 模糊搜索接口
	async searchBlogs() {
		const { ctx, app } = this
		// get 参数
		const { page = 1, size = 5, title } = ctx.query
		const searchBlogs = await app.mysql.query(
			`select * from blogs where title like '%${title}%' limit ? offset ?`,
			[size * 1, (page - 1) * size]
		)
		ctx.body = {
			code: 0,
			msg: 'success',
			data: searchBlogs
		}
	}
}

module.exports = BlogsController
